package com.project.school_flate.serviceimpl.user;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.user.UserInfoDto;
import com.project.school_flate.entity.com.ComDistributionRule;
import com.project.school_flate.entity.com.ComPayFlow;
import com.project.school_flate.entity.com.table.ComDistributionRuleTableDef;
import com.project.school_flate.entity.flow.FlowBusiness;
import com.project.school_flate.entity.flow.FlowMoney;
import com.project.school_flate.entity.flow.FlowTask;
import com.project.school_flate.entity.order.table.OrderTakeawayTableDef;
import com.project.school_flate.entity.shop.ShopSaveUser;
import com.project.school_flate.entity.shop.table.ShopSaveUserTableDef;
import com.project.school_flate.entity.user.UserInfo;
import com.project.school_flate.entity.user.table.UserInfoTableDef;
import com.project.school_flate.mapper.com.ComDistributionRuleMapper;
import com.project.school_flate.mapper.flow.FlowBusinessMapper;
import com.project.school_flate.mapper.flow.FlowMoneyMapper;
import com.project.school_flate.mapper.flow.FlowTaskMapper;
import com.project.school_flate.mapper.order.OrderTakeawayMapper;
import com.project.school_flate.mapper.shop.ShopSaveUserMapper;
import com.project.school_flate.mapper.user.UserInfoMapper;
import com.project.school_flate.service.com.WeiXinPayService;
import com.project.school_flate.service.user.UserInfoService;
import com.project.school_flate.util.HttpClientUtil;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import com.project.school_flate.util.system.ComVariableUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper oUserInfoMapper;

    @Autowired
    private ShopSaveUserMapper oShopSaveUserMapper;

    @Autowired
    private OrderTakeawayMapper oOrderTakeawayMapper;

    @Autowired
    private FlowBusinessMapper oFlowBusinessMapper;

    @Autowired
    private FlowMoneyMapper oFlowMoneyMapper;

    @Autowired
    private ComDistributionRuleMapper oComDistributionRuleMapper;

    @Autowired
    private FlowTaskMapper oFlowTaskMapper;

    @Autowired
    private WeiXinPayService oWeiXinPayService;

    // 微信公众号授权登录请求的网址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    /**
     * 获取用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        List<UserInfo> oUserInfoList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.STATE.eq(1));
        //判断是否传入ID
        if(StringUtils.isNotBlank(oUserInfoDto.getId())){
            queryWrapper.where(UserInfoTableDef.USER_INFO.ID.eq(oUserInfoDto.getId()));
        }
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oUserInfoDto.getPage() != null && oUserInfoDto.getLimit() != null){
            Page<UserInfo> UserInfoPage = oUserInfoMapper.paginateWithRelations(oUserInfoDto.getPage(),oUserInfoDto.getLimit(),queryWrapper);
            oUserInfoList = UserInfoPage.getRecords();
            total = UserInfoPage.getTotalRow();
        }else{
            oUserInfoList = oUserInfoMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oUserInfoList.size();
        }
        //PoToDto
        List<UserInfoDto> oUserInfoDtoList = (List<UserInfoDto>) PoToDTO.poToDtoList(oUserInfoList,new UserInfoDto());
        return Result.ok(oUserInfoDtoList,total);
    }

    /**
     * 添加用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = new UserInfo();
        PoToDTO.poToDto(oUserInfoDto,oUserInfo);
        if(oUserInfoMapper.insert(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加用户失败");
        }
        return Result.ok("添加用户成功");
    }

    /**
     * 修改用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = new UserInfo();
        PoToDTO.poToDto(oUserInfoDto,oUserInfo);
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改用户失败");
        }
        return Result.ok("修改用户成功");
    }

    /**
     * 冻结用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result freezeUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = new UserInfo();
        PoToDTO.poToDto(oUserInfoDto,oUserInfo);
        //判断用户是否还有未完成订单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.USER_ID.eq(oUserInfo.getId()));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.notIn(2,4,6));
        if(CollectionUtils.isNotEmpty(oOrderTakeawayMapper.selectListByQuery(queryWrapper))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("用户还有未完成的订单");
        }
        oUserInfo.setState(0);
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("冻结用户失败");
        }
        return Result.ok("冻结用户成功");
    }

    /**
     * 获取用户（后台）
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getUserInfoBack(UserInfoDto oUserInfoDto) throws Exception {
        List<UserInfo> oUserInfoList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oUserInfoDto.getPage() != null && oUserInfoDto.getLimit() != null){
            Page<UserInfo> UserInfoPage = oUserInfoMapper.paginateWithRelations(oUserInfoDto.getPage(),oUserInfoDto.getLimit(),queryWrapper);
            oUserInfoList = UserInfoPage.getRecords();
            total = UserInfoPage.getTotalRow();
        }else{
            oUserInfoList = oUserInfoMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oUserInfoList.size();
        }
        //PoToDto
        List<UserInfoDto> oUserInfoDtoList = (List<UserInfoDto>) PoToDTO.poToDtoList(oUserInfoList,new UserInfoDto());
        return Result.ok(oUserInfoDtoList,total);
    }

    /**
     * 解冻用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result thawUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = new UserInfo();
        PoToDTO.poToDto(oUserInfoDto,oUserInfo);
        oUserInfo.setState(1);
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("冻结用户失败");
        }
        return Result.ok("冻结用户成功");
    }

    /**
     * 用户填写推广
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result promotionUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        //重新获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oUserInfoDto.getId());
        if(oUserInfo == null){
            return Result.error("当前用户不存在");
        }
        if(StringUtils.isNotBlank(oUserInfo.getInvitationCode())){
            return Result.error("用户已经绑定推广人");
        }
        //获取推广用户信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.TEMP_CODE.eq(oUserInfoDto.getTempCode()));
        UserInfo codeUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
        if(codeUserInfo == null){
            return Result.error("推广用户不存在");
        }
        if(oUserInfo.getId().equals(codeUserInfo.getId())){
            return Result.error("推广人不能绑定自己");
        }
        //修改用户信息
        oUserInfo.setInvitationCode(codeUserInfo.getId());
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改推广用户失败");
        }
        //判断推广用户是否第一次
        if(codeUserInfo.getIsDistribution() == 3){
            codeUserInfo.setIsDistribution(0);
            codeUserInfo.setDistributionGrade(1);
        }
        codeUserInfo.setInvitationNum(codeUserInfo.getInvitationNum() + 1);
        //修改邀请人
        if(oUserInfoMapper.update(codeUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改推广用户失败");
        }
        return Result.ok();
    }

    @Value("${loginTest}")
    private String loginTest;

    /**
     * 用户公众号登录
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result loginUserInfoOfficial(UserInfoDto oUserInfoDto) throws Exception {
        UserInfoDto userInfoDto = new UserInfoDto();
        if(Boolean.valueOf(loginTest)){
            UserInfo oUserInfo = oUserInfoMapper.selectOneById("139538075164479488");
            PoToDTO.poToDto(oUserInfo,userInfoDto);
        }else{
            //需要拿客户端获得的code换取openId
            String url = String.format(WX_LOGIN_URL, ComVariableUtil.getSystemValue("wx_appid"), ComVariableUtil.getSystemValue("wx_secret"), oUserInfoDto.getCode());
            //调用微信api授权
            String data = HttpClientUtil.doGet(url);
            //解析返回的json字符串
            JSONObject jsonObject = JSONObject.parseObject(data);
            //获取openid和token值
            String openId = jsonObject.getString("openid");
            String accessToken = jsonObject.getString("access_token");
            if (StringUtils.isEmpty(openId)) {
                return Result.fail("未获取到openId");
            }
            //通过openId获取用户信息
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(UserInfoTableDef.USER_INFO.WX_OPTION_ID.eq(openId));
            UserInfo oldUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
            if(oldUserInfo == null){
                // 通过openid 和 accessToken 来获取用户信息
                // 拼接请求地址
                String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
                requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
                //发送请求
                String urlRequest = HttpClientUtil.doGet(requestUrl);
                //解析返回的json字符串
                JSONObject userInfo = JSONObject.parseObject(urlRequest);
                //获取用户微信昵称和头像
                String nickname = userInfo.getString("nickname");
                String avatar = userInfo.getString("headimgurl");
                //添加用户
                UserInfo oUserInfo = new UserInfo();
                oUserInfo.setName(nickname);
                oUserInfo.setWxOptionId(openId);
                oUserInfo.setImage(avatar);
                //判断是否传入邀请码，这里的推广方式是链接进入的，所以推广码就是用户ID
                if(StringUtils.isNotBlank(oUserInfoDto.getInvitationCode())){
                    oUserInfo.setInvitationCode(oUserInfoDto.getInvitationCode());
                    //修改邀请人
                    UpdateChain.of(UserInfo.class)
                            .setRaw(UserInfo::getInvitationNum, "invitation_num + " + 1)
                            .where(UserInfo::getId).eq(oUserInfoDto.getInvitationCode())
                            .update();
                }
                //获取所有用户，这里是生成如果是填写推广码要生成的暂存邀请码
                queryWrapper = new QueryWrapper();
                queryWrapper.orderBy("temp_code desc");
                queryWrapper.limit(1);
                UserInfo lastUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
                if(lastUserInfo == null){
                    oUserInfo.setTempCode(1000);
                }else{
                    oUserInfo.setTempCode(lastUserInfo.getTempCode() + 1);
                }
                if(oUserInfoMapper.insert(oUserInfo) == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.error("用户公众号登录失败");
                }
                PoToDTO.poToDto(oUserInfo,userInfoDto);
            }else{
                PoToDTO.poToDto(oldUserInfo,userInfoDto);
            }
        }
        //用户登录
        StpUtil.login(userInfoDto.getId());
        //登录缓存登录对象
        StpUtil.getSession().set("userInfo", userInfoDto);
        userInfoDto.setToken(StpUtil.getTokenValue());
        System.out.println(userInfoDto.getToken());
        return Result.ok(userInfoDto);
    }

    /**
     * 用户绑定手机号
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result bindingUserInfoPhone(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = new UserInfo();
        PoToDTO.poToDto(oUserInfoDto,oUserInfo);
        //判断手机号是否已绑定
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.PHONE.eq(oUserInfo.getPhone()));
        if(oUserInfoMapper.selectOneByQuery(queryWrapper) != null){
            return Result.error("此手机号已被其他微信绑定");
        }
        //获取openId是否被绑定
        queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.WX_OPTION_ID.eq(oUserInfoDto.getWxOptionId()));
        if(oUserInfoMapper.selectOneByQuery(queryWrapper) != null){
            return Result.error("此微信已被其他手机号绑定");
        }
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("用户绑定手机号失败");
        }
        //获取赠送积分规则
        Double money = Double.valueOf(ComVariableUtil.getSystemValue("binding_phone_integral"));
        //创建业务流水
        FlowBusiness oFlowBusiness = new FlowBusiness();
        oFlowBusiness.setType(6);
        oFlowBusiness.setUserId(oUserInfo.getId());
        oFlowBusiness.setInflowDirection(1);
        oFlowBusiness.setInflowWay(1);
        oFlowBusiness.setMoney(money);
        oFlowBusiness.setState(1);
        if(oFlowBusinessMapper.insert(oFlowBusiness) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("用户绑定手机号失败");
        }
        //创建金额流水
        FlowMoney oFlowMoney = new FlowMoney();
        oFlowMoney.setType(6);
        oFlowMoney.setUserId(oUserInfo.getId());
        oFlowMoney.setInflowDirection(1);
        oFlowMoney.setInflowWay(1);
        oFlowMoney.setMoney(money);
        oFlowMoney.setState(1);
        if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("用户绑定手机号失败");
        }
        //添加执行计划
        FlowTask oFlowTask = new FlowTask();
        oFlowTask.setUserId(oUserInfo.getId());
        oFlowTask.setType(6);
        oFlowTask.setMoney(money);
        if(oFlowTaskMapper.insert(oFlowTask) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("用户绑定手机号失败");
        }
        return Result.ok();
    }

    /**
     * 获取用户推广的用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getPromotionUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.INVITATION_CODE.eq(oUserInfoDto.getId()));
        List<UserInfo> oUserInfoList = oUserInfoMapper.selectListByQuery(queryWrapper);
        return Result.ok(oUserInfoList,oUserInfoList.size());
    }

    /**
     * 获取用户推广的储蓄用户
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getSavePromotionUserInfo(UserInfoDto oUserInfoDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTableDef.USER_INFO.INVITATION_CODE.eq(oUserInfoDto.getId()));
        List<UserInfo> oUserInfoList = oUserInfoMapper.selectListByQuery(queryWrapper);
        //创建储蓄会员用户集合
        List<UserInfo> oSaveUserInfoList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(oUserInfoList)){
            //获取查到的用户ID集合
            List<String> oUserInfoIdList = new ArrayList<>();
            oUserInfoList.forEach(item->{oUserInfoIdList.add(item.getId());});
            //查询有哪些用户是储蓄会员
            queryWrapper = new QueryWrapper();
            queryWrapper.where(ShopSaveUserTableDef.SHOP_SAVE_USER.USER_ID.in(oUserInfoIdList));
            List<ShopSaveUser> oShopSaveUserList = oShopSaveUserMapper.selectListByQuery(queryWrapper);
            //获取查到的储蓄用户ID集合
            if(CollectionUtils.isNotEmpty(oShopSaveUserList)){
                List<String> oSaveUserInfoIdList = new ArrayList<>();
                oShopSaveUserList.forEach(item->{oSaveUserInfoIdList.add(item.getId());});
                //获取查到的储蓄用户集合
                for(UserInfo oUserInfo : oUserInfoList){
                    if(oShopSaveUserList.contains(oUserInfo.getId())){
                        oSaveUserInfoList.add(oUserInfo);
                    }
                }
            }
        }
        return Result.ok(oSaveUserInfoList,oSaveUserInfoList.size());
    }

    /**
     * 获取成为专业分销商金额价格
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getInfoSpecialityDistributionMoney(UserInfoDto oUserInfoDto) throws Exception {
        return Result.ok(ComVariableUtil.getSystemValue("speciality_distribution_money"));
    }

    /**
     * 用户成为专业分销商
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result becomeUserInfoSpecialityDistribution(UserInfoDto oUserInfoDto) throws Exception {
        //获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oUserInfoDto.getId());
        if(oUserInfo.getState() == 0){
            return Result.error("用户账号被冻结无法充值");
        }
        if(oUserInfo.getIsDistribution() == 1){
            return Result.error("用户已是专业分销商");
        }
        //创建业务流水
        FlowBusiness oFlowBusiness = new FlowBusiness();
        oFlowBusiness.setType(4);
        oFlowBusiness.setUserId(oUserInfoDto.getId());
        oFlowBusiness.setInflowDirection(0);
        oFlowBusiness.setInflowWay(0);
        oFlowBusiness.setMoney(oUserInfoDto.getSpecialityDistributionMoney());
        if(oFlowBusinessMapper.insert(oFlowBusiness) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("成为分销商失败");
        }
        //创建金额流水
        FlowMoney oFlowMoney = new FlowMoney();
        oFlowMoney.setType(4);
        oFlowMoney.setUserId(oUserInfoDto.getId());
        oFlowMoney.setInflowDirection(0);
        oFlowMoney.setInflowWay(0);
        oFlowMoney.setMoney(oUserInfoDto.getSpecialityDistributionMoney());
        if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("成为分销商失败");
        }
        return Result.ok(oFlowBusiness.getId());
    }

    /**
     * 用户成为专业分销商（回调）
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, String> becomeUserInfoSpecialityDistributionCallback(JSONObject jsonObject) throws Exception {
        try {
            JSONObject returnObject = oWeiXinPayService.notifyOrder(jsonObject);
            System.out.println("-------------------------------------------");
            System.out.println("回调数据" + returnObject);
            System.out.println("-------------------------------------------");
            String outTradeNo = returnObject.get("out_trade_no").toString();
            String attach = returnObject.get("attach").toString();
            //处理微信流水
            UpdateChain.of(ComPayFlow.class)
                    .set(ComPayFlow::getState, 1)
                    .where(ComPayFlow::getType).eq(2)
                    .where(ComPayFlow::getOrderId).eq(outTradeNo)
                    .update();
            if(StringUtils.isNotBlank(attach)){
                Map<String, String> jsonMap = JSONObject.parseObject(attach, new TypeReference<HashMap<String, String>>() {
                });
                becomeUserInfoSpecialityDistributionCallback(jsonMap.get("userId"),Double.valueOf(jsonMap.get("specialityDistributionMoney")));
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
            Map<String, String> res = new HashMap<>();
            res.put("code", "SUCCESS");
            res.put("message", "成功");
            return res;
        }
    }

    /**
     * 用户成为专业分销商（回调业务逻辑）
     * @param userId 客户ID
     * @return
     * @throws Exception
     */
    @Transactional
    public void becomeUserInfoSpecialityDistributionCallback(String userId, Double specialityDistributionMoney) throws Exception {
        //修改业务流水
        UpdateChain.of(FlowBusiness.class)
                .set(FlowBusiness::getState, 1)
                .where(FlowBusiness::getUserId).eq(userId)
                .where(FlowBusiness::getType).eq(4)
                .where(FlowBusiness::getInflowDirection).eq(0)
                .where(FlowBusiness::getInflowWay).eq(0)
                .update();
        //修改金额流水
        UpdateChain.of(FlowMoney.class)
                .set(FlowMoney::getState, 1)
                .where(FlowMoney::getUserId).eq(userId)
                .where(FlowMoney::getType).eq(4)
                .where(FlowMoney::getInflowDirection).eq(0)
                .where(FlowMoney::getInflowWay).eq(0)
                .update();
        //获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(userId);
        oUserInfo.setIsDistribution(1);
        //获取所有的分销商等级规则
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.TYPE.eq(oUserInfo.getIsDistribution()));
        queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.INCOME.ge(oUserInfo.getDistributionPrice()));
        queryWrapper.orderBy("income asc");
        queryWrapper.limit(1);
        ComDistributionRule oComDistributionRule = oComDistributionRuleMapper.selectOneByQuery(queryWrapper);
        if(oComDistributionRule != null && oComDistributionRule.getGrade().compareTo(oUserInfo.getDistributionGrade()) > 0){
            oUserInfo.setDistributionGrade(oComDistributionRule.getGrade());
        }
        if(oUserInfoMapper.update(oUserInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("成为专业分销商失败");
        }
    }

    /**
     * 获取用户分销商等级规则
     * @param oUserInfoDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getUserInfoDistributionGrade(UserInfoDto oUserInfoDto) throws Exception {
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oUserInfoDto.getId());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.GRADE.eq(oUserInfo.getDistributionGrade()));
        queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.TYPE.eq(oUserInfo.getIsDistribution()));
        ComDistributionRule oComDistributionRule = oComDistributionRuleMapper.selectOneByQuery(queryWrapper);
        return Result.ok(oComDistributionRule);
    }

}
